<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;
use User\Model;
/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */

class UserController extends AdminController {

    static protected $allow = array( 'updatePassword','updateNickname','submitPassword','submitNickname');

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
    	$nickname = I('nickname');
    	$map = array('status'=>array('egt',0));
    	if(isset($nickname) && !empty($nickname)){
    		if(intval($nickname) !== 0){
    			$map['uid'] = intval($nickname);
    		}else{
    			$map['nickname']  = array('like', '%'.(string)$nickname.'%');
    		}
    	}

        if (!IS_ROOT) {
            unset($map['uid']);
            $map['uid'] = UID;
        }

        $list   = $this->lists('Member', $map);
   
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $uid = UID;
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User = new UserApi();
        $uid = $User->login($uid, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member = D('Member');
        $data = $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid'=>$uid))->save($data);

        if($res){
        	$user = session('user_auth');
        	$user['username'] = $data['nickname'];
        	session('user_auth', $user);
        	session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
    	$this->meta_title = '修改密码';
        $this->display();
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $uid        =   UID;
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api = new UserApi();
        $res = $Api->updateInfo($uid, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action(){
        //获取列表数据
        $Action = M('Action')->where(array('status'=>array('gt',-1)));
        $list   = $this->lists($Action);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction(){
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign($data);
        $this->meta_title = '编辑行为';
        $this->display();
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            if($res['id']){
                $this->success('更新行为成功！', U('action'));
            }else{
                $this->success('新增行为成功！', U('action'));
            }
        }
    }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus(){
        /*参数过滤*/
        $ids = I('request.ids');
        $status = I('request.status');
        if(empty($ids) || !isset($status)){
            $this->error('请选择要操作的数据');
        }
        //删除缓存
        S('action_list', null);

        /*拼接参数并修改状态*/
        $Model = 'Action';
        $map = array();
        if(is_array($ids)){
            $map['id'] = array('in', implode(',', $ids));
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }
        switch ($status){
            case -1 : $this->delete($Model, $map, array('success'=>'删除成功','error'=>'删除失败'));break;
            case 0 : $this->forbid($Model, $map, array('success'=>'禁用成功','error'=>'禁用失败'));break;
            case 1 : $this->resume($Model, $map, array('success'=>'启用成功','error'=>'启用失败'));break;
            default : $this->error('参数错误');break;
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member', array('uid'=>array('in',$id)) );
                break;
            case 'resumeuser':
                $this->resume('Member', array('uid'=>array('in',$id)) );
                break;
            case 'deleteuser':
                $this->delete('Member', array('uid'=>array('in',$id)) );
                break;
            default:
                $this->error('参数非法');
        }
    }
    
    //登录密码生成
    public function resetpasswd() {       
         
        $inputData =  I();
        if (!IS_POST) {
            $res = M("member")->find($inputData['id']);

            $this->assign('info', $res); 
            $this->display();
        }
        //修改
        if (IS_POST) {
                if(false==$inputData['password'] || false== $inputData['repassword']){
                        $this->error('输入参数错误！');
                }

                if($inputData['password'] != $inputData['repassword']){
                        $this->error('密码和重复密码不一致！');
                }

                $ps = $inputData ['password'];
                $ps_encrypt = $this->ps_encrypt($ps);
                $save = array();
                
                $save['password'] = $ps_encrypt ;
       
                $res = M('UcenterMember')->where("id={$inputData['id']}")->save($save);
                if ($res) {
                      $this->success('操作成功！',U('user/index'));
                }   else {
                     $this->error('操作失败！');
                } 
         }
    }

    //登录密码生成
    public function ps_encrypt($password) {       
        $uc_auth_key = 'cUH-B0idnfK/u=D}`,$tY2<P(O{hJjwx8]7k"1A*';
        $ps_encrypt =  ('' === $password) ? '' : md5(sha1($password) . $uc_auth_key);
        return $ps_encrypt;
    }

    public function add($username = '',$name='', $password = '', $repassword = '', $email = '',$u_type=1){
 
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User = new UserApi;
 
            $uid = $User->register($username, $password, $email,'',$u_type,$name);

            if(0 < $uid){ //注册成功
                $sql = "SELECT work_code FROM ot_ucenter_member WHERE `id`=$uid LIMIT 1";
                $row2 = getrow($sql);

                $user = array('uid' => $uid,'name'=>$name, 'nickname' => $username, 'status' => 1,'u_type'=>$u_type,'work_code'=>$row2['work_code']);
              
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！',U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->getSelectRole();
            $this->display();
        }
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }



    public function alloc(){
       
        $inputData =  I(); 
        $nickname = I('nickname');
        if ($inputData['time-start'])  {
                 $map['registered_time'] = array("EGT",strtotime($inputData['time-start']." 0:0:0"));
          };
        if ($inputData['time-end'])  { 
               $reg_time2 = array("ELT",strtotime($inputData['time-start']." 23:59:59")); 
               $map['registered_time'] = array($map['registered_time'],$reg_time2);
        };
        if ($inputData['fullname'])  { $map['fullname'] = array("LIKE",$inputData['fullname']."%"); };
        if ($inputData['telephone'])  { $map['telephone'] = array("LIKE",$inputData['telephone']); };
        unset($map['time-start'],$map['time-end']);
 
        if (false!=$inputData['queryRole'] ) {
  
 
            $studen_rows = getsql("select studen_id from ot_menber_bind_tag where member_uid in(".$inputData['queryRole'].")");
       
            foreach ($studen_rows as $studen) {
                $s_arr[] = $studen['studen_id'];
            }
 
            $map['id'] = array('in', implode(",", $s_arr) );

         }  
        //活动类型
         if (false!=$inputData['active_type'] ) {
            $map['active_type'] = $inputData['active_type'];
         }
        $list   = $this->lists('Studen', $map);

        foreach ($list as $key => &$value) {
 
            if (false!=$value['birthday']) {
                $value['birthday'] = date("Y-m-d",$value['birthday']) ;
            } else {
                $value['birthday'] =  '';
            }
            false == $value['telephone']  && $value['telephone']='';
            false == $value['registered_time']  && $value['registered_time']='';
            if ($value['generation']) {
                $arr_generation = C("generation");
                $value['generation_name'] = $arr_generation[$value['generation']];
            }
            if ($value['grade']) {
                $arr_grade = C("grade");
                $value['grade_name'] = $arr_grade[$value['grade']];
            }
            
            
            if ($value['admin_work_code']) {  
                $value['admin_name'] = M("member")->where("work_code={$value['admin_work_code']}")->getField('nickname'); 
            }
             

            if ($value['sex']=='') {
                 $value['sex']='';
            } else {
                if (intval($value['sex']) == 1) { $value['sex']='男'; } else { $value['sex']='女'; }
            }
          
                        
            $sql = "SELECT b.`member_uid`,b.`studen_id`,m.`nickname`,b.`u_type`,b.`bind_id`
                FROM `ot_member` m INNER JOIN  `ot_menber_bind_tag` b
                ON (m.`uid` = b.`member_uid`)  WHERE b.`user_status`=TRUE and b.`studen_id`='{$value['id']}' order by u_type asc";
            $res2 = getsql($sql);
             
            $bindArr = array();
            foreach ($res2 as $key2 => $value2) {
                $bindArr[$value2['u_type']] = array("nickname"=>$value2['nickname'],"bind_id"=>$value2['bind_id']);
            }
            if ($bindArr) {
                $value['bindList'] = $bindArr;
            }
        }       
         
        $query_select_role_member = $this->getSelectRoleMember(1,'queryRole','queryRole'); 
        $alloc_select_role_member = $this->getSelectRoleMember(0,'allocRole','allocRole');   
        $this->assign("query_select_role_member",$query_select_role_member) ;
        $this->assign('alloc_select_role_member',$alloc_select_role_member);
       
        $this->assign('select_active_type',$this->get_active_type());
        $this->assign('_list', $list);
        $this->meta_title = '用户分配信息';
        $this->display(); 
    }
	
	
	 public function alloc_del2(){
        $member = M('Member')->where("u_type=3")->select();
        
        $this->assign('_member', $member);

        
        $this->display();   
    }
	

    public function ajaxAllocUserList() {
        $parent   =   I('get.parent');
        //已经分配的客户经理     
        $member1 = M('Member')->where("u_type=2 and status = 1 and parent_lead='{$parent}'")->select();
       
        //没有上层领导人的客户经理
        $member2 = M('Member')->where("u_type=2 and status = 1 and parent_lead=''")->select();
        $content = $this->fetch();

        $this->assign('_member1', $member1);
        $this->assign('_member2', $member2);
        $content = $this->fetch();
        
        $this->ajaxReturn($content);  
    }

    public function saveAlloc(){
        $inputData   =   I('post.');
 
		//绑定处理
        $menber_bind_tag_Model = M('menber_bind_tag'); 
		if (false == $inputData['id']) {
			$this->error("参数未选",U("user/alloc"));
		}
     
		$menber_bind_tag_Model->startTrans();
		$has_error =0 ;
        foreach ($inputData['id'] as $key => $value) {
            if ($value) {
				$data = array();
				$data['studen_id'] = $value; 
                $data['member_uid'] = $inputData['allocRole'] ;
                $data['create_time'] = time();
                $u_type_row = getrow("select u_type from ot_member m where m.uid='{$data['member_uid']}'");
                $data['u_type']  = $u_type_row['u_type'];
  
				$data['doaction'] =  'bind';
 
				$count = $menber_bind_tag_Model->where(array('studen_id'=>$value,'u_type'=>$data['u_type']))->count();
 
				if ($count ==0) {
					$menber_bind_tag_Model->add($data); // 根据条件保存修改的数据  
					//$this->doaction_bindLog($data);		
				} else {
					$has_error ++;
				}				
            }  
        }
		
		if ($has_error>0) {
			// 事务回滚
			$menber_bind_tag_Model->rollback(); 
			$this->error("发现有数据已经分配,不能对已经分配的数据操作" );
		} else {
			//log
			// 提交事务
			$menber_bind_tag_Model->commit();
			$this->success("分配成功");
		}
 
    }
	

    public function unbind() {
        $inputData   =   I('post.');
        $menber_bind_tag_Model = M('menber_bind_tag');
        if (false == $inputData['bind_id'] &&  false == $inputData['studen_id']) {
            $this->error("参数未选",U("user/alloc"));
        }
        
        $res = $menber_bind_tag_Model->where("studen_id='{$inputData['studen_id']}' and bind_id='{$inputData['bind_id']}'")->delete();
  
        $delsql = $menber_bind_tag_Model->getLastSql();  

        $log_path = LOG_PATH."/unbind";
        @mkdir($log_path,0777,true);
        error_log("\r\n\r\n".date("Y-m-d H:i:s")." ".$delsql,3,$log_path."/unbind".date("Y-m-d"));
        if ($res) {
            die(json_encode(array("status"=>"success")));
        } else {
            die(json_encode(array("status"=>"false","msg"=>"操作失败")));
        }
    }

   
	
	 
}
